import { Component, Vue } from 'vue-property-decorator';

interface ChatMessageRequest {
  query: string;
  inputs?: Record<string, any>;
  response_mode: 'streaming' | 'blocking';
  user: string;
  conversation_id?: string;
  files?: Array<{
    type: string;
    transfer_method: 'remote_url' | 'local_file';
    url?: string;
    upload_file_id?: string;
  }>;
  auto_generate_name?: boolean;
}

@Component
export default class LocalStreamHandler extends Vue {
  private buffer = '';
  private controller: AbortController | null = null;
  private isProcessing = false;

  // 发起流式请求
  async fetchLocalStream(request: ChatMessageRequest|any) {
    this.controller = new AbortController();
    
    try {
      const response = await fetch('/dify/v1/chat-messages', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${process.env.VUE_APP_LOCAL_API_KEY}`
        },
        body: JSON.stringify({
          ...request,
          response_mode: 'streaming' // 强制使用流式模式
        }),
        signal: this.controller.signal
      });
      await this.processLocalStream(response);
    } catch (err) {
      if ((err as Error).name !== 'AbortError') {
        this.$emit('stream-error', err);
      }
    }
  }

  private processBuffer() {
    const events = this.buffer.split('\n\n');
    this.buffer = events.pop() || '';

    events.forEach(eventData => {
      try {
        const rawData = eventData.replace(/^data: /, '');
        const data = JSON.parse(rawData);
        
        switch (data.event) {
          case 'message':
            this.$emit('stream-data', data.answer);
            break;
          case 'message_end':
            this.$emit('stream-meta', {
              usage: data.metadata?.usage,
              resources: data.metadata?.retriever_resources
            });
            break;

          case 'message_file':
            this.$emit('stream-file', {
              type: data.type,
              url: data.url,
              belongsTo: data.belongs_to
            });
            break;

          case 'error':
            this.$emit('stream-error', {
              code: data.code,
              message: data.message
            });
            this.abortStream();
            break;

          case 'workflow_started':
          case 'node_started':
          case 'workflow_finished':
            // 处理业务流程事件
            this.$emit('workflow-event', data);
            break;

          case 'ping':
            // 保持连接心跳
            break;

          default:
            console.warn('Unhandled event type:', data.event);
        }
      } catch (err) {
        console.warn('解析事件失败:', err);
      }
    });
  }

  // 处理本地服务数据流
  private async processLocalStream(response: Response) {
    const reader = response.body?.getReader();
    const decoder = new TextDecoder();
    if (!reader) return;

    try {
      let shouldContinue = true
      while (shouldContinue) {
        const { done, value } = await reader.read();
   
        if (done) {
            shouldContinue = false;
            break;
        }
        console.log(value)
        this.buffer += decoder.decode(value);
        this.processBuffer();
      }
      
      // 处理剩余缓冲区数据
      if (this.buffer.length > 0) {
        this.processBuffer();
      }
      
      this.$emit('stream-complete');
    } catch (err) {
      this.$emit('stream-error', err);
    }
  }

  // 终止流
  abortStream() {
    this.controller?.abort();
    this.buffer = '';
  }
}